package com.computergames.server.service.authentication.Implement;
import com.computergames.server.service.Interface.UserService;
import com.computergames.server.service.authentication.Interface.LoginService;
import com.computergames.server.util.JWTUtils;
import com.computergames.server.util.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import org.mindrot.jbcrypt.BCrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class LoginServiceImpl implements LoginService {

    @Autowired
    UserService userService;

//    public LoginServiceImpl(UserService userService) {
//        this.userService = userService;
//    }

    //选手首次登录，验证用户名密码，返回token
    public String GenerateToken(String username, String hashedPassword) {
        //userService = SpringUtil.getBean(UserServiceImpl.class);
        try {
            // 创建用户请求消息
            //LoginRequestMessage user = new LoginRequestMessage();
            //user.setUsername(username);
            //user.setPassword(password);

            // 查找用户
            //LoginRequestMessage loginUser = userService.findUser(user);
            String storedHashedPassword = userService.getStoredHashedPassword(username);

            if (BCrypt.checkpw(hashedPassword, storedHashedPassword)) {
                throw new Exception("用户密码错误或用户不存在");
            }

            // 准备payload数据
            Map<String, String> payload = new HashMap<>();
            payload.put("name", username);
            payload.put("password", hashedPassword); // 注意：通常不建议将明文密码放入token中

            // 生成JWT令牌
            return JWTUtils.getToken(payload);
        } catch (Exception e) { // 自定义服务异常
            // 记录日志（实际应用中需要）
            log.error("生成Token时发生错误: ", e);
            return null;
        }
    }
}


    //选手断线重连，验证token
//    @Override
//    public ApiResponse<?> reconnect(String token){
//        try {
//            // 验证令牌
//            DecodedJWT verify = JWTUtils.verify(token);
//            return new ApiResponse<>(StatusEnum.LOGIN_SUCCESS, "重新连接成功", token);
//        } catch (SignatureVerificationException e) {
//            e.printStackTrace();
//            return new ApiResponse<>(StatusEnum.LOGIN_ERROR, "无效签名", null);
//        }catch (TokenExpiredException e){
//            e.printStackTrace();
//            return new ApiResponse<>(StatusEnum.LOGIN_ERROR, "token过期", null);
//        }catch (AlgorithmMismatchException e){
//            e.printStackTrace();
//            return new ApiResponse<>(StatusEnum.LOGIN_ERROR, "算法不一致", null);
//        }catch (Exception e){
//            e.printStackTrace();
//            return new ApiResponse<>(StatusEnum.LOGIN_ERROR, "token无效", null);
//        }
//    }

